<template>
    <el-card>
        <el-form :inline="true" :model="queryParams">
            <el-form-item label="政策名称">
                <el-input v-model="queryParams.policyName" placeholder="输入政策名称搜索" clearable
                    @keyup.enter="handleSearch" />
            </el-form-item>
            <el-form-item label="所属公司">
                <el-select v-model="queryParams.companyId" placeholder="请选择公司" clearable style="width: 240px;">
                    <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                <el-button type="success" :icon="Plus" @click="handleAdd">新增政策</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="tableData" v-loading="loading" style="width: 100%" border>
            <el-table-column type="index" label="序号" width="80" align="center" :index="calculateIndex" />
            <el-table-column prop="policyName" label="政策名称" min-width="180" />
            <el-table-column prop="companyName" label="所属公司" min-width="160" />
            <el-table-column prop="policyContent" label="政策内容" min-width="250" show-overflow-tooltip />
            <el-table-column prop="effectiveStart" label="生效时间" width="120" />
            <el-table-column prop="effectiveEnd" label="失效时间" width="120" />
            <el-table-column label="状态" width="100" align="center">
                <template #default="{ row }">
                    <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '有效' : '无效' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
            @size-change="fetchData" @current-change="fetchData" style="margin-top: 20px; justify-content: flex-end;" />

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%" @close="resetForm">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
                <el-form-item label="所属公司" prop="companyId">
                    <el-select v-model="form.companyId" placeholder="请选择所属公司">
                        <el-option v-for="item in companyList" :key="item.id" :label="item.companyName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="政策名称" prop="policyName">
                    <el-input v-model="form.policyName" placeholder="请输入政策名称" />
                </el-form-item>
                <el-form-item label="生效日期" prop="effectiveStart">
                    <el-date-picker v-model="form.effectiveStart" type="date" placeholder="选择生效日期"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="失效日期" prop="effectiveEnd">
                    <el-date-picker v-model="form.effectiveEnd" type="date" placeholder="选择失效日期"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="政策内容" prop="policyContent">
                    <el-input v-model="form.policyContent" type="textarea" :rows="5" placeholder="请输入政策内容" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">有效</el-radio>
                        <el-radio :label="0">无效</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
// 引入所有需要的 policy API 函数
import { getPolicyPage, addPolicy, updatePolicy, deletePolicy } from '../../api/policy'
// 引入获取公司列表的函数
import { getCompanyList } from '../../api/company'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'

// --- 响应式状态定义 ---

const tableData = ref([])
const loading = ref(false)
const companyList = ref([]) // 新增：用于存储公司下拉列表

// 查询参数
const queryParams = reactive({
    policyName: '',
    companyId: null
})

// 分页参数
const pagination = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单引用
const formRef = ref(null)

// 表单数据模型
const initialFormState = {
    id: null,
    companyId: null,
    policyName: '',
    policyContent: '',
    effectiveStart: '',
    effectiveEnd: '',
    status: 1
}
const form = reactive({ ...initialFormState })

// 表单校验规则
const rules = {
    companyId: [{ required: true, message: '请选择所属公司', trigger: 'change' }],
    policyName: [{ required: true, message: '请输入政策名称', trigger: 'blur' }],
}

// 核心方法

/**
 * 获取表格数据
 */
const fetchData = async () => {
    loading.value = true
    try {
        const params = {
            pageNum: pagination.pageNum,
            pageSize: pagination.pageSize,
            policyName: queryParams.policyName || null,
            companyId: queryParams.companyId || null
        }
        const data = await getPolicyPage(params)
        tableData.value = data.records
        pagination.total = data.total
    } catch (error) {
        console.error("获取政策列表失败:", error)
    } finally {
        loading.value = false
    }
}

/**
 * 自定义索引计算方法，实现连续序号
 * @param {number} index - 当前行在当前页的索引 (由el-table自动传入)
 */
const calculateIndex = (index) => {
    const currentPage = pagination.pageNum;
    const pageSize = pagination.pageSize;

    return (currentPage - 1) * pageSize + index + 1;
}

/**
 * 获取所有公司列表 (下拉框)
 */
const fetchCompanyList = async () => {
    try {
        companyList.value = await getCompanyList();
    } catch (error) {
        console.error("获取公司列表失败:", error);
    }
}

/**
 * 处理搜索
 */
const handleSearch = () => {
    pagination.pageNum = 1
    fetchData()
}

/**
 * 重置表单到初始状态
 */
const resetForm = () => {
    Object.assign(form, initialFormState);
    formRef.value?.clearValidate();
}

/**
 * 处理新增
 */
const handleAdd = () => {
    resetForm();
    dialogTitle.value = '新增医药政策';
    dialogVisible.value = true;
}

/**
 * 处理编辑
 */
const handleEdit = (row) => {
    resetForm();
    Object.assign(form, row);
    dialogTitle.value = '编辑医药政策';
    dialogVisible.value = true;
}

/**
 * 处理删除
 */
const handleDelete = async (id) => {
    try {
        await ElMessageBox.confirm('确定要删除这条政策吗？', '警告', { type: 'warning' })
        await deletePolicy(id);
        ElMessage.success('删除成功');
        fetchData();
    } catch (error) {
        if (error !== 'cancel') {
            console.error("删除政策失败:", error);
        }
    }
}

/**
 * 提交表单（新增或编辑）
 */
const submitForm = async () => {
    if (!formRef.value) return;
    try {
        await formRef.value.validate();
        if (form.id) {
            await updatePolicy(form);
            ElMessage.success('修改成功');
        } else {
            await addPolicy(form);
            ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        fetchData();
    } catch (validationError) {
        console.log('表单校验失败:', validationError);
    }
}



// --- 生命周期钩子 ---
onMounted(() => {
    fetchData();
    fetchCompanyList(); // 组件挂载时，也要获取公司列表
})
</script>

<style scoped>
.el-form {
    margin-bottom: 20px;
}

.el-select {
    width: 100%;
}
</style>